package com.chenlixian.fishandbearpaw.service.impl;

import com.chenlixian.fishandbearpaw.dao.ShareDao;
import com.chenlixian.fishandbearpaw.dao.UserDao;
import com.chenlixian.fishandbearpaw.entity.Dto.UserLoginDto;
import com.chenlixian.fishandbearpaw.entity.Vo.GeneralVO;
import com.chenlixian.fishandbearpaw.entity.enumEntity.ErrorListEnum;
import com.chenlixian.fishandbearpaw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author chenlixian
 * @description 用户服务层
 * @date 2020/3/15 17:30
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private ShareDao shareDao;
    @Override
    public UserLoginDto login(UserLoginDto userLoginDto) {
        UserLoginDto user = userDao.login(userLoginDto);
        return user;

    }

    @Override
    public String register(UserLoginDto userLoginDto) {
        UserLoginDto user = userDao.getUserByName(userLoginDto.getUserName());
        if (user != null)
            return "用户已存在";
        else {
           Integer count = userDao.register(userLoginDto);
           if (count == 1)
               return "注册成功";
           else
               return "注册失败";
        }
    }

    @Override
    public GeneralVO favorite(Integer userId, Integer fUserId, Integer isFavorite) {
        Integer count = 0;
        if (isFavorite == 1){
            count = userDao.cancelFavorite(userId,fUserId);
            if (count == 1)
                return new GeneralVO(ErrorListEnum.E200,"取消关注成功");
        }
        else{
            count = userDao.favorite(userId,fUserId);
            if (count == 1){
                if (fUserId != userId)
                    shareDao.addMessage(fUserId,userId,2);
                return new GeneralVO(ErrorListEnum.E200,"关注成功");
            }

        }
        return null;

    }

    @Override
    public List<UserLoginDto> queryUserRandom(Integer userId) {
        Integer count = userDao.queryUserCount(userId);
        Integer random = new Random().nextInt(count/3);
        List<UserLoginDto> users = userDao.queryUserRandom(userId,random*3);
        return users;
    }
}
